<template>
  <div class="page course-edit">
    <div style="font-size: 20px" class="pb-24 align-center">
      <el-page-header @back="$router.push({ name: 'course-list'})" :content="isNew ? '添加课程' : '编辑课程'" />
    </div>
    <div class="justify-center form-container" v-if="!isLoading">
      <el-form
        :model="formData"
        inline
        label-width="120px"
        ref="form"
        size="small">
        <el-row>
          <el-form-item label="课程名称" prop="name">
            <el-input v-model="formData.name" style="width: 400px"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="一级分类" prop="firstCategory">
            <el-select v-model="formData.firstCategory" placeholder="请选择" @change="firstCategoryChange">
              <el-option
                v-for="item in firstCategoryList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类" prop="secondCategory">
            <el-select v-model="formData.secondCategory" placeholder="请选择">
              <el-option
                v-for="item in secondCategoryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="描述" prop="introduction">
            <el-input
              style="width: 400px"
              type="textarea"
              maxlength="60"
              show-word-limit
              :autosize="{ minRows: 4, maxRows: 6}"
              placeholder="在课程详情页标题下面展示卖点信息，建议60字以内"
              v-model="formData.introduction">
            </el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="图标" prop="coverUrl">
            <uploader :src.sync="formData.coverUrl" ></uploader>
            <div class="tips">建议尺寸：800*800像素</div>
          </el-form-item>
          <el-form-item label="视频" v-if="isNew || formData.videoUrl">
            <uploader :src.sync="formData.videoUrl" :videoId.sync="formData.videoId"  type="video"></uploader>
            <div class="tips">文件大小不超过300mb，比例为1:1,16:9或者3:4，时长不超过60s</div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="轮播图" prop="pictureUrl">
            <upload-list :list.sync="formData.pictureUrl" style="max-width: 900px" :max="15"></upload-list>
            <div class="tips">建议尺寸：1200*790p像素，最多上传15张</div>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="售价（元）" prop="salePrice">
            <el-input-number v-model="formData.salePrice" :controls="false" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item label="原价（元）" prop="price">
            <el-input-number v-model="formData.price" :controls="false" :precision="2"></el-input-number>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="拼团价（元）" prop="grouponPrice">
            <el-input-number v-model="formData.grouponPrice" :controls="false" :precision="2"></el-input-number>
          </el-form-item>
          <el-form-item label="成团人数" prop="grouponPeople">
            <el-input-number v-model="formData.grouponPeople" :controls="false"></el-input-number>
          </el-form-item>
        </el-row>
        <el-form-item label="课程详情" prop="courseInfo">
          <rich-text v-model="formData.courseInfo"></rich-text>
        </el-form-item>
        <el-row>
          <el-form-item label="限时课程" prop="timeLimitCourse">
            <el-switch v-model="formData.timeLimitCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="最新课程" prop="latestCourse">
            <el-switch v-model="formData.latestCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="热门课程" prop="hotCourse">
            <el-switch v-model="formData.hotCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="拼团课程" prop="grouponCourse">
            <el-switch v-model="formData.grouponCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="美术主推" prop="commendArtCourse">
            <el-switch v-model="formData.commendArtCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="书法主推" prop="commendCalligraphyCourse">
            <el-switch v-model="formData.commendCalligraphyCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
          <el-form-item label="弹框课程" prop="advertisementCourse">
            <el-switch v-model="formData.advertisementCourse" :active-value="1" :inactive-value="0"></el-switch>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="formData.sort" :controls="false"></el-input-number>
          </el-form-item>
          <el-form-item label="课程节数" prop="captherCount">
            <el-input-number v-model="formData.captherCount" :controls="false"></el-input-number>
          </el-form-item>
          <el-form-item label="学龄" prop="studentAgeId">
            <el-select v-model="formData.studentAgeId" placeholder="请选择">
              <el-option
                v-for="item in studentAgeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="课程内容" class="video-form-item">
          <el-button type="primary" @click="addChapter">添加小节</el-button>
          <div v-for="(chapter, index) in formData.chapterList" :key="index" class="pt-24">
            <div class="pb-24 align-center">
              <div class="f-16 pr-24">{{`第 ${index + 1} 节`}}</div>
              <div class="pr-24">标题</div>
              <el-input v-model="chapter.name" style="width: 220px"></el-input>
              <i class="el-icon-delete pl-24 f-20 delete" @click="delChapter(index)" v-if="formData.chapterList.length > 1"></i>
            </div>
            <div class="video-section py-24 px-32">
              <div v-for="(section, videoIndex) in chapter.sectionList" :key="videoIndex" class="align-center pb-24">
                <div class="pr-24">{{`第${videoIndex + 1}关`}}</div>
                <div class="pr-24">标题</div>
                <el-input v-model="section.name" style="width: 220px;" class="pr-24"></el-input>
                <div class="pr-8">时长</div>
                <div class="pr-24">{{section.videoTime | formatTime }}</div>
                <uploader
                  type="video"
                  :name="section.videoUrl"
                  :videoId.sync="section.videoId"
                  :duration.sync="section.videoTime"
                  :src.sync="section.videoUrl">
                </uploader>
                <i class="el-icon-delete pl-24 f-20 delete" @click="delSection(index, videoIndex)" v-if="chapter.sectionList.length > 1"></i>
              </div>
              <el-button type="primary" @click="addSection(index)">添加关卡</el-button>
            </div>
          </div>
        </el-form-item>
        <div class="flex-center">
          <el-button type="primary" @click="save" style="width: 200px">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { saveCourse, getCourseInfo, updateCourse } from '@/api/course';
import { getFirstCategoryList, getSecondCategoryList, getStudentAgeOptions } from '@/utils';

export default {
  data() {
    return {
      isLoading: true,
      studentAgeOptions: [],
      formData: {
        name: '',
        firstCategory: '',
        secondCategory: '',
        introduction: '',
        coverUrl: '',
        pictureUrl: [],
        videoId: '',
        videoUrl: '',
        price: undefined,
        salePrice: undefined,
        grouponPrice: undefined,
        grouponPeople: undefined,
        courseInfo: '',
        timeLimitCourse: 0,
        latestCourse: 0,
        hotCourse: 0,
        grouponCourse: 0,
        commendArtCourse: 0, // 美术主推
        commendCalligraphyCourse: 0, // 书法主推
        advertisementCourse: 0,
        sort: undefined,
        captherCount: undefined,
        chapterList: [
          {
            name: '',
            sectionList: [
              {
                name: '',
                videoTime: 0,
                videoId: '',
                videoUrl: '',
              },
            ],
          },
        ],
      },
      firstCategoryList: [],
      secondCategoryList: [],
      secondCategoryOptions: [],
      isCreate: false,
    };
  },
  computed: {
    isNew() {
      const { courseId } = this.$route.query;
      return !courseId;
    },
  },
  filters: {
    formatTime(val) {
      if (val) {
        let hours = Math.floor((val / 60 / 60) % 24);
        let minutes = Math.floor((val / 60) % 60);
        let seconds = Math.floor((val) % 60);
        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        seconds = seconds < 10 ? '0' + seconds : seconds;
        return `${hours}:${minutes}:${seconds}`;
      }
      return '00:00:00';
    },
  },
  methods: {
    addChapter() {
      this.formData.chapterList.push({
        name: '',
        sectionList: [{
          name: '',
          videoTime: '',
          videoUrl: '',
          videoId: '',
        }],
      });
    },
    delChapter(index) {
      this.formData.chapterList.splice(index, 1);
    },
    delSection(index, videoIndex) {
      this.formData.chapterList[index].sectionList.splice(videoIndex, 1);
    },
    addSection(index) {
      this.formData.chapterList[index].sectionList.push({
        name: '',
        videoTime: '',
        videoUrl: '',
        videoId: '',
      });
    },
    async getCategoryOptions() {
      const [firstCategoryList, secondCategoryList] = await Promise.all([
        getFirstCategoryList(),
        getSecondCategoryList(),
      ]);
      this.firstCategoryList = firstCategoryList;
      this.secondCategoryList = secondCategoryList;
      this.secondCategoryOptions = secondCategoryList;
    },
    async getStudentAgeOptions() {
      this.studentAgeOptions = await getStudentAgeOptions();
    },
    firstCategoryChange(val) {
      this.formData.secondCategory = '';
      this.secondCategoryOptions = this.secondCategoryList.filter((item) => item.parentId === val);
    },
    validChapterList(chapterList) {
      for (let i = 0; i < chapterList.length; i++) {
        const { name, sectionList } = chapterList[i];
        if (!name.trim()) {
          return false;
        }
        for (let j = 0; j < sectionList.length; j++) {
          const { name: sectionName } = sectionList[j];
          if (!sectionName.trim()) {
            return false;
          }
        }
      }
      return true;
    },
    async save() {
      try {
        const {
          price, salePrice, grouponPrice, chapterList,
        } = this.formData;
        const valid = this.validChapterList(chapterList);
        if (!valid) {
          this.$message.error('课程标题不能为空');
          return;
        }
        const params = {
          ...this.formData,
          price: price * 100,
          salePrice: salePrice * 100,
          grouponPrice: grouponPrice * 100,
          pictureUrl: this.formData.pictureUrl.join(','),
        };
        const { courseId } = this.$route.query;
        if (courseId) {
          await updateCourse({
            ...params,
            courseId,
          });
        } else {
          await saveCourse(params);
        }
        this.$message.success('保存成功');
        this.$router.push({ name: 'course-list' });
      } catch (err) {
        this.$message.error('保存失败');
      }
    },
  },
  async created() {
    this.isLoading = true;
    await Promise.all([
      this.getCategoryOptions(),
      this.getStudentAgeOptions(),
    ]);
    const { courseId } = this.$route.query;
    if (courseId) {
      const { course } = await getCourseInfo({ courseId: Number(courseId) });
      const {
        pictureUrl, price, salePrice, grouponPrice,
      } = course;
      this.formData = {
        ...course,
        price: price / 100,
        salePrice: salePrice / 100,
        grouponPrice: grouponPrice / 100,
        pictureUrl: pictureUrl.split(','),
      };
    }
    this.isLoading = false;
  },
};
</script>
<style lang="scss" scoped>
  .course-edit {
    .form-container {
      height: calc(100vh - 190px);
      overflow-y: auto;
      &::-webkit-scrollbar {
        display: none;
      }
      .tips {
        color: #606266;
        font-size: 12px;
      }
      .video-form-item {
        .video-section {
          border: 1px solid #CCC;
        }
        .delete {
          cursor: pointer;
        }
      }
    }

  }
</style>
<style>
  .el-select-dropdown {
    z-index: 100000 !important;
  }
</style>
